package com.example.imagetest;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int PERMISSION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 检查是否有写入外部存储的权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 如果没有权限，请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
        } else {
            // 如果已经有权限，那么直接去下载图片
            downloadImage();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 检查权限请求的结果
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 如果权限授予，则开始下载图片
                downloadImage();
            } else {
                // 如果权限拒绝，那么旧纪录错误日志
                Log.e(TAG, "Permission denied");
            }
        }
    }

    /**
     * 下载图片并进行展示
     */
    private void downloadImage() {
        OkHttpClient client = new OkHttpClient();
        // 这里使用的是百度的logo图片，可以直接访问下载，没有安全验证等拦截机制
        String url = "https://www.baidu.com/img/bd_logo1.png";

        // 创建请求对象
        Request request = new Request.Builder()
                .url(url)
                .build();

        // 异步调用enqueue方法来发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败时回调
                e.printStackTrace();
                Log.e(TAG, "下载图片失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功时回调
                if (response.isSuccessful()) {
                    InputStream inputStream = null;
                    FileOutputStream outputStream = null;
                    try {
                        inputStream = response.body().byteStream();
                        // 图片保存路径：/storage/emulated/0/Android/data/
                        // 创建一个文件对象来保存下载的图片
                        File file = new File(getExternalFilesDir(null), "downloaded_image.jpg");
                        outputStream = new FileOutputStream(file);

                        byte[] buffer = new byte[2048];
                        int bytesRead;
                        // 将输入流写入文件输出流
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }

                        // 在主线程上更新UI以显示下载的图片
                        runOnUiThread(() -> displayImage(file.getAbsolutePath()));
                        // 记录图片保存的位置
                        Log.d(TAG, "图片保存位置：" + file.getAbsolutePath());
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e(TAG, "保存图片失败: " + e.getMessage());
                    } finally {
                        // 关闭输入流和输出流
                        if (inputStream != null) inputStream.close();
                        if (outputStream != null) outputStream.close();
                    }
                } else {
                    Log.e(TAG, "请求失败，响应码: " + response.code());
                }
            }
        });
    }

    /**
     * 在UI层显示图片
     *
     * @param imagePath
     */
    private void displayImage(String imagePath) {
        ImageView imageView = findViewById(R.id.imageView);
        // 将图片文件解码为Bitmap
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        // 显示下载的图片
        imageView.setImageBitmap(bitmap);
    }
}